<?php


namespace app\controller\api;


use app\BaseController;
use think\facade\Db;

class ProductController extends BaseController
{
    /**
     * 商品列表
     * @return \think\response\Json
     */
    public function getProductList()
    {
        try {
            $page = $this->page;
            $limit = $this->limit;
            $list = Db::name('product')
                ->where('status', 0)
                ->paginate(['list_rows' => $limit, 'page' => $page])
                ->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function getProductInfo()
    {
        try {
            $id = $this->request->param('id');
            $info = Db::name('product')
                ->where('status', 0)->where('id', $id)->find();
            return $this->success($info);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 兑换商品
     * @return \think\response\Json
     */
    public function exchangeProduct()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id');
            if (!$id) {
                throw new \Exception("商品ID错误");
            }
            $productInfo = Db::name('product')->where('id', $id)->where('status', 0)->find();
            if (!$productInfo) {
                throw new \Exception("商品不存在或已下架");
            }
            if ($productInfo['stock'] <= 0) {
                throw new \Exception("商品库存不足");
            }
            $addressId = $this->request->param('aid');
            if (!$addressId) {
                throw new \Exception("请选择地址");
            }
            $addressInfo = Db::name('user_address')->where('id', $addressId)->where('status', 0)->find();
            if (!$addressInfo) {
                throw new \Exception("地址不存在");
            }
            $userId = $this->request->userId;
            $score = $productInfo['price'];
            $userInfo = Db::name('user')->where('id', $userId)->find();
            if ($userInfo['score'] < $score) {
                throw new \Exception("上架费不足");
            }
            Db::name('user')->where('id', $userId)->dec('score', $score)->update();
            Db::name('user')->where('id', $userId)->inc('exchange', $score)->update();
            Db::name('product')->where('id', $id)->dec('stock')->update();
            $orderSn = createExchangeOrderSn();
            Db::name('exchange_order')->insert([
                'paint_id' => $this->request->paintId,
                'user_id' => $userId,
                'goods_id' => $id,
                'address_id' => $addressId,
                'order_sn' => $orderSn,
                'order_status' => 1,
                'goods_name' => $productInfo['goods_name'],
                'goods_img' => $productInfo['goods_img'],
                'goods_price' => $productInfo['price'],
                'user_name' => $addressInfo['user_name'],
                'user_phone' => $addressInfo['phone'],
                'user_address' => $addressInfo['full_address'],
                'create_time' => time(),
                'update_time' => time(),
            ]);
            Db::name('detailed_score')->insert([
                'user_id' => $userId,
                'user_name' => $userInfo['user_name'],
                'type' => 0,
                'money' => $score,
                'balance' => $userInfo['score'],
                'order_sn' => $orderSn,
                'create_time' => date('Y-m-d H:i:s'),
                'remark' => '上架费兑换商品'
            ]);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 兑换列表
     * @return \think\response\Json
     */
    public function getExchangeList()
    {
        try {
            $type = $this->request->param('type', 0, 'int');
            $where = [];
            $where[] = ['user_id', '=', $this->request->userId];
            if ($type) {
                $where[] = ['order_status', '=', $type];
            }
            $page = $this->page;
            $limit = $this->limit;
            $list = Db::name('exchange_order')
                ->where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $limit, 'page' => $page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $v['create_time'] = date('Y-m-d\TH:i:s', $v['create_time']);
                $v['update_time'] = date('Y-m-d\TH:i:s', $v['update_time']);
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}